import axios from 'axios';
import Vue from 'vue'
import {
    BASE_URL,
    url_name_1,
    url_name_3
} from "@/axios/Global"
/**
 * 上传文件
 */
export const uploadUrl = `${BASE_URL}${url_name_3}/sys-fdfs-file/uploadImg`;
export const uploadCert = `${BASE_URL}${url_name_3}/sys-fdfs-file/uploadFile`;

// 下载Excel
export function exportExcel(data, filename) { // data为二进制流，filename为文件名称
    const blob = new Blob([data], {
        type: 'application/zip;charset=utf-8'
    })
    const fileName = `${filename}.xlsx` // 下载的文件名称及其后缀，后缀要和后台保持的一致
    if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
    } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
    }
}

export function infoMsg(message) {
    Vue.prototype.$message({
        type: "info",
        message: message
    });
}
export function successMsg(message) {
    Vue.prototype.$message({
        type: "success",
        message: `${message}成功`
    });
}
export function error(data) {
    let msg = data.data || data.msg || '服务器异常！请稍后再试'
    Vue.prototype.$message({
        type: "error",
        message: msg
    });
}
export function Error(message) {
    Vue.prototype.$message({
        type: "error",
        message: message
    });
}
export function errorMsg(err, message) {
    const msg = (err.msg || err.message) ? (err.msg ? err.msg : err.message) : `${message}`;
    Vue.prototype.$message({
        type: "error",
        message: msg
    });
}

export function scrollHeight() {
    document.querySelector(
        '.scrollable .el-table__body-wrapper'
    ).scrollTop = document.querySelector(
        '.scrollable .el-table__body-wrapper'
    ).scrollHeight
}

/**
 * 获取文字拼音码
 * @param {String} name 名称
 */
export function getPinyin(name) {
    return new Promise((resolve, reject) => {
        axios.get(`${url_name_1}/common/pinyin`, {
            params: {
                name
            }
        }).then(response => {
            resolve(response);
        }, err => {
            reject(err)
        })
    })
}

/**
 * 获取文字拼音码
 * @param {String} name 名称
 */
export function getWubin(name) {
    return new Promise((resolve, reject) => {
        axios.get(`${url_name_1}/common/wubi`, {
            params: {
                name
            }
        }).then(response => {
            resolve(response);
        }, err => {
            reject(err)
        })
    })
}

// 格式化时间
export function formatDate(time, flag) {
    var date = new Date(time);
    var fmt = flag ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd';
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        S: date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length == 1 ?
                o[k] :
                ("00" + o[k]).substr(("" + o[k]).length)
            );
    return fmt;
}


/**
 * 查询所有物资
 * @param {String} materialName 物资名称
 * @param {Number} pageIndex 第几页
 * @param {Number} pageNum 每页多少条
 * @param {Number} materialType 	1为普通耗材 2 为定数包
 */

export function getMaterialPlan(materialName, materialType, pageNum, pageSize) {
    return new Promise((resolve, reject) => {
        axios.get(`${url_name_1}/purchase-plan/v1/material/list`, {
            params: {
                materialName,
                materialType,
                pageNum,
                pageSize
            }
        }).then(response => {
            resolve(response);
        }, err => {
            reject(err)
        })
    })
}

/**
 * 获取所有的仓库
 */

export function warehousesList() {
    return new Promise((resolve, reject) => {
        axios.get(`${url_name_1}/im-material-storage/v1/warehouses/list`).then(response => {
            resolve(response);
        }, err => {
            reject(err)
        })
    })
}

// 只能输入正浮点数
export function limitFloat(value, target, name, bit=5) {
    let val = null
    if (value !== '') {
        if (value.indexOf('.') > -1) {
            val = value.slice(0, value.indexOf('.') + bit)
        } else {
            val = value
        }
        target[name] = val
    }
}

// 只能输入正整数
export function limitInt(target, name) {
    if (target[name] && typeof(target[name]) == Number) {
        if (!target[name]) return
        let str = target[name] + '';
        target[name] = parseInt(str.replace(/[^0-9]/g, ""));
        this.$set(target, name, target[name])
    } else {
        let str = target[name] + '';
        target[name] = str.replace(/[^0-9]/g, "");
    }

}

/**
 * 删除附件ByPath
 * @param {Number} id 文件id
 */

export function deleteFile(path) {
    return new Promise((resolve, reject) => {
        axios.post(`${url_name_1}/sys-fdfs-file/deleteFileByPath?path=${path}`).then(response => {
            resolve(response);
        }, err => {
            reject(err)
        })
    })
}

// 获取数据类型
export function getDataType(obj) {
    var typeArr = ["String", "Object", "Number", "Array", "Date"];
    for (let name of typeArr) {
        if (Object.prototype.toString.call(obj) === `[object ${name}]`) {
            return name;
        }
    }
}

export function returnFloat(value) {
    if (value) {
        var xsd = value.toString().split('.');
        if (xsd.length === 1) {
            value = value.toString() + '.0000';
            return value;
        }
        if (xsd.length > 1) {
            if (xsd[1].length == 1) {
                value = value.toString() + '000';
            }
            if (xsd[1].length == 2) {
                value = value.toString() + '00';
            }
            if (xsd[1].length == 3) {
                value = value.toString() + '0';
            }
            if (xsd[1].length == 0) {
                value = value.toString() + '0000';
            }
            return value;
        }
    } else {
        return value
    }
}